import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { NulResponse, createEmptyRequest, createRequest } from "./common";
import { RootState } from "./store";
import { cloneArray } from "../util/Arrays";
import { getRequest } from "../util/Auth";

interface UserEntry {
  id: number;
  name: string;
  userName: string;
  gender: string;
  authority: string;
}

interface UserState {
  fetched: boolean;
  entries: UserEntry[];
}

interface UserRequest {
  name: string;
  userName: string;
  gender: string;
  authority: string;
}

interface CreateUserResponse {
  id: number;
}

interface UserDeleteRequest {
  id: number[];
}

const userInitialState: UserState = {
  fetched: false,
  entries: []
};

export const fetchAllUserEntries = createAsyncThunk('api/fetchAllUserEntries', async (_, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<UserEntry[]>>('/service/user/fetchAll',
      createEmptyRequest());
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const createNewUser = createAsyncThunk('api/createNewUser', async (user: UserRequest, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CreateUserResponse>>('/service/user/createEntry',
      createRequest(user));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const modifyUser = createAsyncThunk('api/modifyUser', async (user: UserEntry, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<CreateUserResponse>>('/service/user/modifyEntry',
      createRequest(user));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const deleteUser = createAsyncThunk('api/deleteUser', async (id: number[], { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('/service/user/deleteEntry',
      createRequest<UserDeleteRequest>({ id }));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

const userSlice = createSlice({
  name: 'user',
  initialState: userInitialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(fetchAllUserEntries.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(fetchAllUserEntries.fulfilled, (state, action) => {
      state.fetched = true;
      state.entries = action.payload.result;
    }).addCase(createNewUser.fulfilled, (state, action) => {
      console.log(action.payload);
      const entry: UserEntry = {
        ...action.meta.arg,
        ...action.payload.result
      };
      state.entries.push(entry);
      state.entries.sort((a, b) => a.id - b.id);
    }).addCase(createNewUser.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(modifyUser.fulfilled, (state, action) => {
      const index: number = state.entries.findIndex(item => item.id === action.meta.arg.id);
      if (index !== -1) {
        state.entries[index] = action.meta.arg;
      }
    }).addCase(modifyUser.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(deleteUser.fulfilled, (state, action) => {
      const deletedIds: number[] = cloneArray(action.meta.arg);
      const userEntries: UserEntry[] = state.entries;
      deletedIds.sort();
      const result: UserEntry[] = [];
      for (let i = 0, j = 0; j < userEntries.length; ++j) {
        if (userEntries[j].id !== deletedIds[i])
          result.push(userEntries[j]);
        else ++i;
      }
      state.entries = result;
    }).addCase(deleteUser.rejected, (state, action) => {
      console.error(action.error);
    });
  }
});

export type { UserEntry };
export const { actions } = userSlice;
export const selectUserEntries = (state: RootState) => state.userManagementReducer.entries;
export const selectUserFetched = (state: RootState) => state.userManagementReducer.fetched;
export default userSlice.reducer;